﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

/*
 * Author:Conis
 * Date:
 * Description:Xml的基础组件
 */

namespace Coins.Squirrel.Nodous.Xml
{
    public abstract class XmlNodousComponent
    {
        protected List<XmlNodousComponent> list;          //保存节点列表
        protected bool isSafe = false;                  //是否为安全的值，安全的值不包括Xml的敏感字符串
        protected XmlElement parentElement;             //父级
        protected XmlDocument container;
        protected string name;
        protected string value;
        public XmlNodousComponent Parent { get; set; }

        /// <summary>
        /// Xml节点的抽象类
        /// </summary>
        /// <param name="name">节点的名称</param>
        /// <param name="value">节点的值</param>
        protected internal XmlNodousComponent(string name, string value)
        {
            this.list = new List<XmlNodousComponent>();
            this.name = name;
            this.value = value;
        }

        /// <summary>
        /// 添加节点
        /// </summary>
        /// <param name="c"></param>
        protected void Add(XmlNodousComponent c)
        {
            this.list.Add(c);
        }

        /// <summary>
        /// 删除节点
        /// </summary>
        /// <param name="c"></param>
        protected void Remove(XmlNodousComponent c)
        {
            this.list.Remove(c);
        }

        /// <summary>
        /// 根据索引删除节点
        /// </summary>
        /// <param name="index"></param>
        public void RemoveAt(int index)
        {
            if (index < 0 || index >= this.list.Count)
            {
                return;
            }
            this.list.RemoveAt(index);
        }

        /// <summary>
        /// 创建
        /// </summary>
        protected void Create()
        {
            int index = 1;
            this.CreateNode();
            foreach (XmlNodousComponent item in this.list)
            {
                item.container = this.container;
                item.parentElement = this.parentElement;
                item.Create();
                index++;
            }
        }

        /// <summary>
        /// 创建具体节点
        /// </summary>
        protected virtual void CreateNode()
        {
            XmlElement element = this.container.CreateElement(this.name);
            this.parentElement.AppendChild(element);
            this.parentElement = element;
        }
    }
}
